/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.server.modules.sys.web.loan;

import com.server.common.config.Global;
import com.server.common.persistence.Page;
import com.server.common.utils.StringUtils;
import com.server.common.web.BaseController;
import com.server.modules.api.service.IMService;
import com.server.modules.api.service.MaterialUploadAPIService;
import com.server.modules.api.vo.LoanDto;
import com.server.modules.sys.entity.User;
import com.server.modules.sys.entity.bank.Bank;
import com.server.modules.sys.entity.home.HomeImg;
import com.server.modules.sys.entity.loan.*;
import com.server.modules.sys.entity.material.MaterialType;
import com.server.modules.sys.entity.member.Member;
import com.server.modules.sys.entity.tag.Tag;
import com.server.modules.sys.service.SystemService;
import com.server.modules.sys.service.bank.BankService;
import com.server.modules.sys.service.home.HomeImgService;
import com.server.modules.sys.service.loan.*;
import com.server.modules.sys.service.material.MaterialTypeService;
import com.server.modules.sys.service.member.MemberService;
import com.server.modules.sys.service.tag.TagService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 贷款Controller
 * @author 颜洪毅/傅友园
 * @version 2016-10-11
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/loan/loan")
public class LoanController extends BaseController {
	
	 @Resource
	 protected IMService imService;

	@Autowired
	private LoanService loanService;

	@Autowired
	private LoanTypeService loanTypeService;

	@Autowired
	private MaterialTypeService materialTypeService;


	@Autowired
	private LoanMaterialtypeReService loanMaterialtypeReService;
	
	@Autowired
	private HomeImgService homeImgService;
	

	@Autowired
	private MemberService memberService;


	@Autowired
	private BankService bankService;

	@Autowired
	private LoanManagerService loanManagerService;
    @Autowired
    private SystemService systemService;

	@Autowired
	private TagService tagService;
    @Autowired
    private LoanTagsService loanTagsService;
    @Autowired
	private MaterialUploadAPIService materialUploadAPIService;



	@ModelAttribute
	public Loan get(@RequestParam(required=false) String id) {

		Loan entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = loanService.get(id);
		}
		if (entity == null){
			entity = new Loan();
		}
		return entity;
	}

	@RequiresPermissions("sys:loan:loan:view")
	@RequestMapping(value = {"list", ""})
	public String list(Loan loan, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Loan> page = loanService.findPage(new Page<Loan>(request, response), loan);
		model.addAttribute("page", page);
		model.addAttribute("loan", loan);
		//获取贷款资料类型以便设置贷款资料类型的时候取值
		MaterialType materialType=new MaterialType();
		MaterialType parent=new MaterialType("0");
		materialType.setParent(parent);
		model.addAttribute("rootTypes",  materialTypeService.findList(materialType));
		//渠道银行
		model.addAttribute("banks",bankService.findList(new Bank()));
		model.addAttribute("bankName",loan.getBankName());
		model.addAttribute("bankId",loan.getBankId());
		return "modules/sys/loan/loanList";
	}

	@RequiresPermissions("sys:loan:loan:view")
	@RequestMapping(value = "form")
	public String form(Loan loan, Model model) {
		model.addAttribute("types", loanTypeService.findList(new LoanType()));
		model.addAttribute("banks", bankService.findList(new Bank()));
		model.addAttribute("loan", loan);
		return "modules/sys/loan/loanForm";
	}

	@RequiresPermissions("sys:loan:loan:checkermanager")
	@RequestMapping(value = "checker")
	public String checker(Member member, Model model,HttpServletRequest request, HttpServletResponse response) {
		Page<Member> page = loanService.checkList(new Page<Member>(request, response), member);
		//1.根据产品id查询出该产品所需要的资料
		model.addAttribute("page",page);
		model.addAttribute("loanId",member.getLoanId());
		//2.t_material_upload这张表里面查出所满足条件的用户
		return "modules/sys/loan/loanMemberCheck";
	}

	@RequiresPermissions("sys:loan:loan:edit")
	@RequestMapping(value = "save")
	public String save(Loan loan, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, loan)){
			return form(loan, model);
		}
		loanService.save(loan);
		addMessage(redirectAttributes, "保存贷款成功");
		return "redirect:"+Global.getAdminPath()+"/sys/loan/loan/?repage";
	}

	@RequiresPermissions("sys:loan:loan:edit")
	@RequestMapping(value = "saveMeterial")
	public String saveMeterial(Loan loan,String[] materialTypes, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, loan)){
			return form(loan, model);
		}
		if(materialTypes==null||materialTypes.length<1){
			loanMaterialtypeReService.deleteByLoanId(loan.getId());
		}else{
			loanMaterialtypeReService.saveByLoanId(loan.getId(),materialTypes);
		}
		addMessage(redirectAttributes, "保存贷款资料成功");
		return "redirect:"+Global.getAdminPath()+"/sys/loan/loan/?repage";
	}



	@RequiresPermissions("sys:loan:loan:edit")
	@RequestMapping(value = "delete")
	public String delete(Loan loan, RedirectAttributes redirectAttributes) {
		loanService.delete(loan);
		addMessage(redirectAttributes, "删除贷款成功");
		return "redirect:"+Global.getAdminPath()+"/sys/loan/loan/?repage";
	}

	/**
	 * 设置轮播图
	 * @param loan
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:loan:loan:addhomeimg")
	@RequestMapping(value = "addHomeImg")
	public String addHomeImg(Loan loan, Model model) {
		model.addAttribute("loan", loan);
		HomeImg homeImg=new HomeImg();
		homeImg.setObjId(loan.getId());
		List<HomeImg> hi = homeImgService.findList(homeImg);
		if(!CollectionUtils.isEmpty(hi)){
			loan.setHomeImg(hi.get(0));
		}
		
		return "modules/sys/loan/addHomeImg";
	}

	/**
	 *设置贷款资料
	 * @param loan
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:loan:loan:setmaterial")
	@RequestMapping(value = "material")
	public String material(Loan loan, Model model) {
		MaterialType materialType=new MaterialType();
		materialType.setParent(new MaterialType("0"));
		List<MaterialType> list = materialTypeService.findList(materialType);
		model.addAttribute("list", list);
		LoanMaterialtypeRe loanMaterialtypeRe=new LoanMaterialtypeRe();
		loanMaterialtypeRe.setLoanId(loan.getId());
		model.addAttribute("loanMaterials", loanMaterialtypeReService.findList(loanMaterialtypeRe));
		model.addAttribute("loan", loan);
		return "modules/sys/loan/material";
	}
	/**
	 *设置贷款标签
	 * @param loan
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:loan:loan:settags")
	@RequestMapping(value = "tags")
	public String tag(Loan loan, Model model) {
        Tag tag = new Tag();
        tag.setTypeId("-1");
        List<Tag> tags = tagService.findList(tag);
        LoanTags loanTags=new LoanTags();
        loanTags.setLoanId(loan.getId());
        model.addAttribute("tags", tags);
		model.addAttribute("loanTagss",  loanTagsService.findList(loanTags));
		model.addAttribute("loan", loan);
		return "modules/sys/loan/tags";
	}
    @RequiresPermissions("sys:loan:loan:edit")
    @RequestMapping(value = "saveTags")
    public String saveTags(Loan loan,String[] tagsIds, Model model, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, loan)){
            return form(loan, model);
        }
        if(tagsIds==null||tagsIds.length<1){
            loanTagsService.deleteByLoanId(loan.getId());
        }else{
            loanTagsService.saveByLoanId(loan.getId(),tagsIds);
        }
        addMessage(redirectAttributes, "保存贷款资料成功");
        return "redirect:"+Global.getAdminPath()+"/sys/loan/loan/?repage";
    }

	/**
	 * 设置客户经理
	 * @param user
	 * @param loan
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequiresPermissions("sys:loan:loan:setmanager")
	@RequestMapping(value = "manager")
	public String manager(User user, Loan loan, Model model, HttpServletRequest request, HttpServletResponse response) {
        LoanManager loanManager = new LoanManager();
        loanManager.setLoanId(loan.getId());
        List<LoanManager> list = loanManagerService.findList(loanManager);
        for (LoanManager lm:list ) {
            lm.setUser(systemService.getUser(lm.getUserId()));
        }
        model.addAttribute("loanManagers", list);
		model.addAttribute("loan", loan);
        Page<User> userPage = new Page<>(request, response);
        userPage.setPageSize(10);
        userPage.setPageNo(0);
        model.addAttribute("page", userPage);
		return "modules/sys/loan/manager";
	}
	@RequiresPermissions("sys:loan:loan:setmanager")
    @RequestMapping(value = "saveManagers")
    public String saveManagers(Loan loan,String[] managers, Model model, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, loan)){
            return form(loan, model);
        }
        if(managers==null||managers.length<1){
            loanManagerService.deleteByLoanId(loan.getId());
        }else{
            loanManagerService.saveByLoanId(loan.getId(),managers);
        }
        addMessage(redirectAttributes, "保存【"+loan.getName()+"】的客服人员成功");
        return "redirect:"+Global.getAdminPath()+"/sys/loan/loan/?repage";
    }

    @RequiresPermissions("sys:loan:loan:view")
    @RequestMapping(value = "load/userList")
    public String loadUuserList(User user, Loan loan, Model model, HttpServletRequest request, HttpServletResponse response) {
        Page<User> userPage = new Page<>(request, response);
        userPage.setPageSize(10);
        Page<User> page = systemService.findUser(userPage, user);
        model.addAttribute("page", page);
        return "modules/sys/loan/load/userList";
    }

	@RequiresPermissions("sys:loan:loan:edit")
	@RequestMapping(value = "homeImgSave")
	public String homeImgSave(Loan loan, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, loan.getHomeImg())){
			return addHomeImg(loan, model);
		}
		HomeImg homeImg = loan.getHomeImg();
		String id = loan.getId();
		homeImg.setObjId(id);
		homeImg.setOrderids("1");
		homeImgService.save(homeImg);
		return "redirect:"+Global.getAdminPath()+"/sys/loan/loan/?repage";
	}
	
	@RequiresPermissions("sys:loan:loan:edit")
	@RequestMapping(value = "setOrCancerBoutique")
	@ResponseBody
	public Object setOrCancerBoutique(Loan loan,Boolean isPush, Model model, RedirectAttributes redirectAttributes) {
		if(!StringUtils.isBlank(loan.getId())){
			Boolean boutiqueFlag = loan.getBoutiqueFlag();
			if(boutiqueFlag==null){
				loan.setBoutiqueFlag(true);
			}else if(boutiqueFlag){
				loan.setBoutiqueFlag(false);
			}else if(!boutiqueFlag){
				loan.setBoutiqueFlag(true);
			}
			
			loanService.save(loan);
			Boolean boutiqueFlag2 = loan.getBoutiqueFlag();
			//已经设置了精品套餐 要推送服务(推给所有用户)
			if(boutiqueFlag2&&isPush){
				List<Member> findList = memberService.findList(new Member());
				List<String> userList = new ArrayList<String>(1);
				for (Member member : findList) {
					userList.add(member.getHxUsername());
				}
                Map<String,String > msg = new HashedMap();
                msg.put("type","text");
                StringBuffer bf=new StringBuffer("精品套餐：向您推荐精品套餐【");
                bf.append(loan.getName()).append("】,欢迎使用！");
                msg.put("msg",bf.toString());
                Map<String,String > ext = new HashedMap();
                ext.put("objId",loan.getId());
                ext.put("type","1");//1为产品，2为申请记录，3为URL
				//imService.sendMessages("users",userList,msg,"客服经理",ext);
				imService.sendSysMessages(userList,msg,ext);
			}
			
			return true;
		}
		
		return false;
	}
	
	@RequiresPermissions("sys:loan:loan:setrecomend")
	@RequestMapping(value = "setOrCancerRecomend")
	@ResponseBody
	public Object setOrCancerRecomend(Loan loan,Boolean isPush, Model model, RedirectAttributes redirectAttributes) {
		if(!StringUtils.isBlank(loan.getId())){
			Boolean recomendFlag = loan.getRecomendFlag();
			if(recomendFlag==null){
				loan.setRecomendFlag(true);
			}else if(recomendFlag){
				loan.setRecomendFlag(false);
			}else if(!recomendFlag){
				loan.setRecomendFlag(true);
			}
			
			loanService.save(loan);
			Boolean recomendFlag2 = loan.getRecomendFlag();
			//已经设置了新品推荐 要推送服务(推给所有用户)
			if(recomendFlag2&&isPush){
				List<Member> findList = memberService.findList(new Member());
				List<String> userList = new ArrayList<String>(1);
				for (Member member : findList) {
					userList.add(member.getHxUsername());
				}
                Map<String,String > msg = new HashedMap();
                msg.put("type","text");
                StringBuffer bf=new StringBuffer("新品推荐：本公司新品【");
                bf.append(loan.getName()).append("】上架,欢迎使用！");
                msg.put("msg",bf.toString());
                Map<String,String > ext = new HashedMap();
                ext.put("objId",loan.getId());
                ext.put("type","1");//1为产品，2为申请记录
				//imService.sendMessages("users",userList,msg,"客服经理",ext);
				imService.sendSysMessages(userList,msg,ext);
			}
			
			return true;
		}
		
		return false;
	}

	@RequiresPermissions("sys:loan:loan:edit")
	@RequestMapping(value = "getById")
	@ResponseBody
	public Object getById(Loan loan) {
		return loan;
	}


    @RequiresPermissions("sys:loan:loan:getmaterialtypename")
	@RequestMapping(value = "getMaterialTypeNames")
	public ModelAndView getMaterialTypeNames(){
		ModelAndView mx = new ModelAndView();
		List<MaterialType> materialTypes = 	loanService.getMaterialTypeNames();
		mx.addObject("materialTypes",materialTypes);
		mx.setViewName("/modules/sys/loan/datumCheckLoan");
		return mx;
	}

    @RequestMapping(value = "getLoanListFilters")
	@ResponseBody
	public Object getLoanListFilters(String ids){
		String[] str  = ids.split(",");
		List<String> stringList = new ArrayList<>();
		for (int i = 0;i < str.length;i++){
			stringList.add(str[i]);
		}
		List<LoanDto> loans = loanService.getMaterialTypeLoans(stringList);
		for(int i=0;i<loans.size();i++){
			System.out.println(loans.get(i));
		}
		return loans;
	}

	@RequestMapping(value = "getImgurl")
	public String getImgurl(String url,Model model){
		String urls = url;
		model.addAttribute("urls",urls);
		return "modules/sys/loan/load/bigimg";
	}



}